<template>
  <div id="app">
    <header class="header">
      <div class="logo"></div>
      <span class="line"></span>
      <span class="header-title">通行证</span>
    </header>
    <h1 class="title">来闻文化点评社交平台</h1>
    <div class="modal" v-if="isInfor">
      <!-- 隐藏手机号登录 -->
      <!-- <div class="infor-login" v-if="show">
        <div class="code-btn" @click="showCode()">
          <img src="../assets/imgs/loginCode.png" alt title="扫码登录" />
        </div>
        <div class="top">
          <div class="login">短信登录</div>
        </div>
        <input
          placeholder="手机号"
          class="phone"
          v-model="phone"
          :class="borderShow ? '' : 'borderRed'"
        />
        <div class="code">
          <input placeholder="验证码" class="phone-code" v-model="code" />
          <button class="btn" @click="getPiccode" :disabled="disable">{{ text }}</button>
        </div>
        <Geet :isGeet="isgt" @geetPath="GeetPath" @clickChange="GeetChange"></Geet>
        <div class="login-btn" @click="login()" @keyup.enter="login">登录</div>
        <div class="auto-login"></div>
      </div> -->
      <!-- v-else -->
      <div class="code-login"  v-loading="loading">
        <div class="codeTop">
          <div class="code-btn PCcode" @click="showCode()">
            <img src="../assets/imgs/PCcode.png" alt title="短信登录" />
          </div>
          <h2 class="prompt">微信二维码登录</h2>
        </div>
        <div id="qrcode">
          <wxlogin :appid="appid" :scope="snsapi_login" :redirect_uri="redirect_uri" :href="href"></wxlogin>
        </div>
        <!-- 
        <p>请使用微信扫描二维码登录</p>
        <div class="way">
        </div>-->
      </div>
    </div>
    <FinishInfor v-else></FinishInfor>
    <footer>
      Copyright © 2020 Nanjing Sidieji Network Technology Co., Ltd. All rights
      reserved.
    </footer>
  </div>
</template>
<script>
import wxlogin from "vue-wxlogin";
import FinishInfor from "../components/FinishInfor";
import Geet from "../components/Geet";
import axios from "axios";
export default {
  name: "login",
  props: {},
  data() {
    return {
      Checkvalue: false,
      show: true,
      code: "",
      phone: "",
      borderShow: true,
      text: "获取验证码",
      number: 60,
      disable: false,
      appid: "",
      snsapi_login: "",
      redirect_uri: "",
      href: "",
      isInfor: true,
      loading: false,
      isCodeLogin: false,
      codeObj: null,
      isgt: false,
      isPicCheck: false, //图形验证码校验
    };
  },
  watch: {
    //监听手机号
    phone: {
      handler(newName, oldName) {
        let reg = /^[1][3,4,5,7,8][0-9]{9}$/;
        if (reg.test(newName)) {
          this.borderShow = true;
        } else {
          this.borderShow = false;
        }
      },
      // immediate: true,
    },
    // $route: {
    //   handler: function(val, oldVal) {
    //     this.codeLogin();
    //   },
    //   deep: true,
    // },

    //监听图形验证码
    isPicCheck: {
      handler(newVal, oldVal) {
        if (newVal) {
          this.getCode();
        }
      },
    },
  },

  created() {
    this.watchHistory();
    //监听Url变化
    this.appid = "wx93d8456fc07e21cc";
    this.snsapi_login = "snsapi_login";
    this.redirect_uri = "https%3a%2f%2fwww.laismell.com%2f%23%2flogin";
    this.href =
      "data:text/css;base64,LmltcG93ZXJCb3ggLnFyY29kZSB7d2lkdGg6IDIwMHB4O30NCi5pbXBvd2VyQm94IC50aXRsZSB7ZGlzcGxheTogbm9uZTt9DQouaW1wb3dlckJveCAuaW5mbyB7d2lkdGg6IDIwMHB4O30NCi5zdGF0dXNfaWNvbiB7ZGlzcGxheTogbm9uZX0NCi5pbXBvd2VyQm94IC5zdGF0dXMge3RleHQtYWxpZ246IGNlbnRlcjt9IA==";
  },
  components: { wxlogin, FinishInfor, Geet },
  mounted() {
    this.getRem(1920, 100);
  },
  methods: {
    //监听二维码扫码登录
    //参数：为code
    codeLogin(code) {
      if (code) {
        //显示二维码登录
        this.show = false;
        //加载loading
        this.loading = true;
        localStorage.setItem("isFirstExpire", false);
        //通过用code换取用户信息
        this.$fetch(`/laiwen/WXuser/login/codeLogin?code=${code}`).then(
          (res) => {
            if (res.code == 500 || res.code == "40001") {
              this.$message.error("登录出错请联系管理员");
            } else {
              //缓存用户信息
              localStorage.setItem("user", JSON.stringify(res.user));
              //缓存openid
              localStorage.setItem("openid", JSON.stringify(res.openid));

              this.loading = false;
              //判断用户的答题状态0=>显示信息补全页,1=>find页并存储token
              if (res.user.answerStatus == null || res.user.answerStatus == 0) {
                this.isInfor = false;
              } else {
                localStorage.setItem("token", res.token);
                this.$router.push({
                  path: "/",
                });
              }
            }
          }
        );
      } else {
        this.$message.warning("二维码登录错误请联系管理员");
      }
    },
    register() {
      this.$router.push({
        path: "/register",
      });
    },
    messageLogin() {
      this.showCode();
    },
    //展示二维码
    showCode() {
      this.show = !this.show;
    },
    //获取验证码
    getCode() {
      if (
        this.borderShow == true &&
        this.disable == false &&
        this.isPicCheck == true
      ) {
        this.disable = true;
        this.timer(60);
        this.$post(
          `/laiwen/message/frontend/test?phoneNumber=${this.phone}`,
          {}
        ).then((res) => {});
      }
    },
    //图形验证码
    getPiccode() {
      // 手机号不能为空
      if (this.phone === "") {
        this.$message.error("请填写手机号");
        return false;
      }
      console.log("2,按钮被点击，进行图形验证");
      this.isgt = !this.isgt;

      //只进行一次图形验证码校验
      //重新发送不校验
      // if (this.text != "重新发送") {
      // } else {
      //   this.disable = true;
      //   this.timer(60);
      // }
    },
    //手机号登录
    login() {
      localStorage.setItem("isFirstExpire", false);
      this.$fetch(
        `/laiwen/user/frontend/login?code=${this.code}&phone_number=${this.phone}`,
        {}
      ).then((res) => {
        //1.答题成功=>主页  2.未答题=>信息补全  3.输入的验证码或没有注册=>error
        if (res.msg == "success" || res.msg == "登录成功") {
          //第一种
          if (res.user.answerStatus === 1) {
            //存储user
            localStorage.setItem("user", JSON.stringify(res.user));
            //存储token
            localStorage.setItem("token", res.token);
            this.$router.push({
              path: "/",
            });
          } else {
            //第二种
            localStorage.setItem("user", JSON.stringify(res.user));
            this.isInfor = false;
          }
        } else {
          this.$message.error("输入的验证码有误或者没有注册哦");
        }
      });
    },
    //60秒倒计时
    timer(num) {
      let time = setInterval(() => {
        if (num > 0) {
          num--;
          this.text = `${num}秒`;
        } else {
          this.text = `重新发送`;
          clearInterval(time);
          this.disable = false;
          this.isPicCheck = false;
        }
      }, 1000);
    },
    //监听histroy
    watchHistory() {
      window.addEventListener("popstate", (e) => {
        console.log(e.currentTarget.location.href);
        let url = e.currentTarget.location.href;
        let parmaCode = e.currentTarget.location.href.split("=")[1];
        //参数中带有code时,才进行校验
        if (url.indexOf("code") != -1) {
          this.codeLogin(parmaCode);
        }
      });
    },

    // 极验图片加载之后，通过更改控制变量实现可以再次加载
    GeetChange(val) {
      this.isgt = val;
    },
    //获取图形验证码参数
    GeetPath(val) {
      console.log("4,接受到图形验证参数，将参数发往服务端进行验证");
      console.log(val);
      this.isgt = false;
      this.$post(`/laiwen/geetest/frontend/secinit`, val).then((res) => {
        //判断验证码状态
        if (res.iscode == 1) {
          this.isPicCheck = true;
        }
      });
    },
  },
  beforeRouteUpdate(to, from, next) {},
};
</script>

<style scoped src="../assets/css/login.css"></style>
